﻿using System.Drawing;
using System.Reflection;
using Colorful;
using FreeSql;
using FreeSqlTest.BackgroundServices;
using FreeSqlTest.Configs;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NLog;
using NLog.Extensions.Logging;
using Yitter.IdGenerator;
using Console = Colorful.Console;

namespace FreeSqlTest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var font = FigletFont.Load("big.flf");
            var figlet = new Figlet(font);
            Console.WriteLine(figlet.ToAscii("SMOM DEV CONSOLE"));

            var logger = LogManager.Setup().GetCurrentClassLogger();
            try
            {
                logger.Debug("application is initializing...");

                var host = CreateHostBuilder(args).Build();
                // 创建 IdGeneratorOptions 对象，可在构造函数中输入 WorkerId：
                var options = new IdGeneratorOptions(1);
                YitIdHelper.SetIdGenerator(options);
                Console.WriteLine(YitIdHelper.NextId());

                var assemblies = Assembly.Load(nameof(OrmTestDomain));
                var types = assemblies.GetTypes()
                    .Where(o => o.Name.EndsWith("Entity"))
                    .ToList();
                var freeSql = host.Services.GetRequiredService<IFreeSql>();
                // Console.WriteLine(freeSql.CodeFirst.GetComparisonDDLStatements(types.ToArray()));

#if DEBUG
                freeSql.CodeFirst.SyncStructure(types.ToArray());
#endif

                host.Run();
            }
            catch (Exception exception)
            {
                logger.Error(exception, "Stopped program because of exception");
            }
            finally
            {
                LogManager.Shutdown();
            }
        }


        public static IHostBuilder CreateHostBuilder(string[] args)
        {


            // // 创建 IdGeneratorOptions 对象，可在构造函数中输入 WorkerId：
            // var options = new IdGeneratorOptions(27);
            // YitIdHelper.SetIdGenerator(options);
            return Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostingContext, builder) =>
                {
                    var c = builder.Build();

                    builder.SetBasePath(AppDomain.CurrentDomain.BaseDirectory);
                    builder.AddJsonFile("appsettings.json");

                    builder.AddCommandLine(args);
                })
                .ConfigureServices((hostContext, services) =>
                {
                    Func<IServiceProvider, IFreeSql> fsqlFactory = r =>
                    {
                        var fsql = new FreeSqlBuilder()
                            .UseConnectionString(DataType.SqlServer,
                                                 @"Data Source=172.16.10.140;Initial Catalog=sMOMDEV_Performance;User Id=sa;Password=IP06c0;")
                            .UseMonitorCommand(cmd => Console.WriteLine($"Sql：{cmd.CommandText}",
                                                                        Color.Green)) //监听SQL语句
                            .UseAutoSyncStructure(true) //自动同步实体结构到数据库，FreeSql不会扫描程序集，只有CRUD时才会生成表。
                            .Build();
                        return fsql;
                    };
                    services.AddSingleton(fsqlFactory);
                    services.AddSingleton<ConsoleConfig>();
                    // services.AddHostedService<FreeSqlDefaultTestService>();
                 //   services.AddHostedService<FreeSqlTableSplitTestService>();
                 services.AddHostedService<DynamicLinqTestService>();

                })
                .ConfigureLogging((context, builder) => builder.AddNLog("nlog.config"));
        }
    }
}
